package com.albert.View;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageButton;
import android.widget.PopupWindow;

import com.albert.iotcar.R;

public class TopActionBarPopup {

    private final PopupWindow popupWindow;
    private final View contentView;
    private final Activity activity;
    private final View anchorToolbar;

    private ImageButton mBtPick;
    private ImageButton mBtHang;
    private TopActionBarCallback topActionBarCallback;

    public TopActionBarPopup(Activity activity, View anchorToolbar, TopActionBarCallback topActionBarCallback) {
        this.activity = activity;
        this.anchorToolbar = anchorToolbar;
        this.topActionBarCallback = topActionBarCallback;

        LayoutInflater inflater = LayoutInflater.from(activity);
        contentView = inflater.inflate(R.layout.layout_top_popup, null);

        // 圆角背景
        GradientDrawable bgDrawable = new GradientDrawable();
        bgDrawable.setCornerRadius(dpToPx(activity, 16));
        bgDrawable.setColor(Color.WHITE);
        bgDrawable.setStroke(dpToPx(activity, 1), Color.LTGRAY);
        contentView.setBackground(bgDrawable);

        popupWindow = new PopupWindow(
                contentView,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true
        );

        // 不让系统直接关闭
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(null);
        popupWindow.setElevation(10f);

        // 监听外部点击（通过 TouchInterceptor）
        popupWindow.setTouchInterceptor((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                // 点击区域不在 contentView 内部
                int[] loc = new int[2];
                contentView.getLocationOnScreen(loc);
                float x = event.getRawX();
                float y = event.getRawY();

                boolean inside = x >= loc[0] && x <= loc[0] + contentView.getWidth()
                        && y >= loc[1] && y <= loc[1] + contentView.getHeight();

                if (!inside) {
                    dismiss(); // 自定义动画关闭
                    return true; // 拦截事件
                }
            }
            return false;
        });

        mBtPick = contentView.findViewById(R.id.view_call_trying_imageButton_pick);
        mBtHang = contentView.findViewById(R.id.view_call_trying_imageButton_hang);

        mBtPick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pickHangCall(true);
            }
        });
        mBtHang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pickHangCall(false);
            }
        });
    }

    private void pickHangCall(boolean isPick) {
        if (topActionBarCallback == null) {
            dismiss();
            return;
        }
        if (isPick){
            topActionBarCallback.pickUpCall();
        }else{
            topActionBarCallback.handUpCall();
        }
        dismiss();
    }

    public void show() {
        int screenWidth = activity.getResources().getDisplayMetrics().widthPixels;
        int marginPx = dpToPx(activity, 16); // 左右各16dp
        int popupWidth = screenWidth - marginPx * 2;

        popupWindow.setWidth(popupWidth);

        View rootView = activity.getWindow().getDecorView();
        int yOffset = (anchorToolbar != null) ? anchorToolbar.getHeight() : getActionBarSize(activity);
        popupWindow.showAtLocation(rootView, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, yOffset);

        // 显示动画（下滑）
        contentView.setTranslationY(-contentView.getHeight());
        contentView.setAlpha(0f);
        contentView.post(() -> {
            ObjectAnimator slideIn = ObjectAnimator.ofFloat(contentView, "translationY", -contentView.getHeight(), 0);
            slideIn.setDuration(220);
            slideIn.setInterpolator(new DecelerateInterpolator());

            ObjectAnimator fadeIn = ObjectAnimator.ofFloat(contentView, "alpha", 0f, 1f);
            fadeIn.setDuration(220);

            slideIn.start();
            fadeIn.start();
        });
    }

    public void dismiss() {
        contentView.post(() -> {
            ObjectAnimator slideOut = ObjectAnimator.ofFloat(contentView, "translationY", 0, -contentView.getHeight());
            slideOut.setDuration(220);
            slideOut.setInterpolator(new DecelerateInterpolator());

            ObjectAnimator fadeOut = ObjectAnimator.ofFloat(contentView, "alpha", 1f, 0f);
            fadeOut.setDuration(220);

            slideOut.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    popupWindow.dismiss();
                }
            });

            slideOut.start();
            fadeOut.start();
        });
    }

    private int getActionBarSize(Context context) {
        TypedValue tv = new TypedValue();
        if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            return TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
        }
        return 0;
    }

    private int dpToPx(Context context, int dp) {
        return Math.round(dp * context.getResources().getDisplayMetrics().density);
    }
}
